<template>
    <div>
        {{time.h}}:{{time.m}}:{{time.s}}
    </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
    props: {
        endTime: {
            type: Number,
            default: 0
        },
    },
    data() {
        return {
            serverTime: 0,
            time: {
                h: '00',
                m: '00',
                s: '00'
            }
        }
    },
    computed: {
        ...mapState(['currentTime'])
    },
    mounted() {
        this.$nextTick(() => {
            this.setServerTime()
            this.getCountDown()
        })
    },
    methods: {
        getCountDown() {
            if (this.serverTime !== 0 && this.endTime > this.serverTime) { // 正确获取到系统时间，开始计算倒计时
                let diffTime = this.endTime - this.serverTime
                let h = '', m = '', s = '';
                h = Math.floor(diffTime / 1000 / 60 / 60).toString().padStart(2, '0');
                m = Math.floor(diffTime / 1000 / 60 % 60).toString().padStart(2, '0');
                s = Math.floor(diffTime / 1000 % 60).toString().padStart(2, '0');
                this.time = { h, m, s };
                this.endTime += 1000
            }
            this.timer2 = setTimeout(() => {
                this.getCountDown()
            }, 1000)
        },
        setServerTime() {
            this.serverTime = this.currentTime
            clearTimeout(this.timer1)
            this.timer1 = setTimeout(() => {
                this.setServerTime()
            }, 30000)
        }
    },
    beforeDestroy() {
        clearTimeout(this.timer1) // 获取系统时间的定时器
        clearTimeout(this.timer2) // 计算倒计时的定时器
    }
}
</script>

<style scoped>

</style>